package com.fullstack.repository;

import com.fullstack.user.AbstractUser;
import com.fullstack.util.FileService;
import com.fullstack.util.FileServiceImpl;

import java.io.File;
import java.io.IOException;

/**
 * @program: fullstackdayone
 * @Description:
 * @author: Mr.Cheng
 * @date: 2021/10/13 3:28 下午
 */
public class UserRepositoryFromFile implements UserRepository{
    /**
     * @param user
     * @Description: find user information by name
     * @Param: [name]
     * @return: com.fullstack.user.AbstractUser
     * @Author: Mr.Cheng
     * @Date: 2021/10/13 3:18 下午
     */
    @Override
    public AbstractUser findUserByname(AbstractUser user) {
        File userFile = new File("./users/" + user.getName() + ".txt");
        if(userFile.exists()){
            FileService fileService = new FileServiceImpl();
            String[] userDetail = fileService.fileReading(userFile);
            user.setPassword(userDetail[1]);
            user.setName(userDetail[0]);
            return user;
        }
        return null;
    }

    /**
     * @param user
     * @Description: save user information
     * @Param: [user]
     * @return: java.lang.Boolean
     * @Author: Mr.Cheng
     * @Date: 2021/10/13 3:23 下午
     */
    @Override
    public Boolean saveUser(AbstractUser user) {
        File userFile = new File("./users/" + user.getName() + ".txt");
        if(!userFile.exists()){
            try {
                userFile.createNewFile();
            } catch (IOException e) {

            }
            String[] userDetail = {user.getName(), user.getPassword()};
            FileService fileService = new FileServiceImpl();
            Integer index = fileService.fileWriting(userFile, userDetail);
            return index == 2 ;
        }
        return null;
    }
}
